package com.njtoyo.taxi.admin.service.business.ride.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.library.common.util.CopyUtil;
import com.njtoyo.taxi.admin.mapper.master.entity.Ride;
import com.njtoyo.taxi.admin.mapper.master.entity.RideMarking;
import com.njtoyo.taxi.admin.mapper.master.entity.Tag;
import com.njtoyo.taxi.admin.mapper.master.mapper.RideMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.RideMarkingMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.RideMarkingTagMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.TagMapper;
import com.njtoyo.taxi.admin.rest.export.RideMarkingListData;
import com.njtoyo.taxi.admin.rest.presenter.business.ride.marking.*;
import com.njtoyo.taxi.admin.rest.presenter.platfrom.AdminUserIdentityPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.ride.marking.RideMarkingExportWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.business.ride.marking.RideMarkingWrapper;
import com.njtoyo.taxi.admin.service.business.ride.RideMarkingService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

@Service
public class RideMarkingServiceImpl implements RideMarkingService {
    @Autowired
    private RideMapper rideMapper;
    @Autowired
    private RideMarkingTagMapper rideMarkingTagMapper;
    @Autowired
    private RideMarkingMapper rideMarkingMapper;
    @Autowired
    private TagMapper tagMapper;

    /**
     * 所有的标签
     *
     * @return
     */
    @Override
    public RestResult<List<TagListDataPresenter>> tagList() {
        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.select("id", "title");
        List<Tag> tags = tagMapper.selectList(tagQueryWrapper);
        List<TagListDataPresenter> res =
                CopyUtil.copyList(tags, TagListDataPresenter.class);
        return RestResult.success(res);
    }

    /**
     * 评价列表
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    public RestResult<Page<RideMarkingPagePresenter>> evaluationList(AdminUser adminUser, RideMarkingWrapper wrapper) {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        switch (adminUser.getAccountType()) {
            case canton:
                wrapper.setCantonIds(identity.getCantonIds());
                break;
            case company:
                wrapper.setCompanyIds(identity.getCompanyIds());
        }
        if (StrUtil.isNotBlank(wrapper.getStartDate()) && StrUtil.isNotBlank(wrapper.getEndDate())) {
            wrapper.setStartDate(wrapper.getStartDate() + " 00:00:00");
            wrapper.setEndDate(wrapper.getEndDate() + " 23:59:59");
        }
        Page<RideMarkingPagePresenter> evaluationPage = rideMarkingMapper.rideMarkingPage(wrapper);
        List<Long> ids = evaluationPage.getRecords().stream()
                .map(RideMarkingPagePresenter::getId)
                .collect(toList());
        if (ObjectUtils.isEmpty(ids)) {
            return RestResult.success(evaluationPage);
        }
        //查询标签
        List<RideMarkingTagData> rideMarkingTags = rideMarkingTagMapper.selectTags(ids);
        Long[] longs = new Long[0];
        for (RideMarkingPagePresenter e : evaluationPage.getRecords()) {
            ArrayList<Long> list = new ArrayList<>();
            Long id = e.getId();
            e.setTag(longs);
            for (RideMarkingTagData r : rideMarkingTags) {
                String tagIdss = r.getTagId();
                String[] split = tagIdss.split(",");
                if (r.getMarkingId().equals(id)) {
                    for (int i = 0; i < split.length; i++) {
                        Long aLong = Long.valueOf(split[i]);
                        list.add(aLong);
                        Long[] tagid = list.toArray(new Long[list.size()]);
                        e.setTag(tagid);
                    }
                }
            }
        }
        return RestResult.success(evaluationPage);
    }

    /**
     * 评价列表导出Excel
     *
     * @param wrapper
     * @param response
     * @return
     * @throws IOException
     */
    @Override
    public RestResult export(RideMarkingExportWrapper wrapper, AdminUser adminUser, HttpServletResponse response) throws IOException {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        switch (adminUser.getAccountType()) {
            case canton:
                wrapper.setCantonIds(identity.getCantonIds());
                break;
            case company:
                wrapper.setCompanyIds(identity.getCompanyIds());
        }
        Integer count = rideMarkingMapper.evaluationCounts(wrapper);
        if (count > 6000) {
            return RestResult.failed("数据量过大");
        }
        List<RideMarkingListData> evaluationListData = rideMarkingMapper.evaluationList(wrapper);
        //查询标签
        List<Long> ids = evaluationListData.stream()
                .map(RideMarkingListData::getId)
                .collect(toList());
        if (!ObjectUtils.isEmpty(ids)) {
            List<TagTitleData> tagTitleList = rideMarkingTagMapper.selectTagTitle(ids);
            for (RideMarkingListData e : evaluationListData) {
                for (TagTitleData r : tagTitleList) {
                    Long id = e.getId();
                    if (r.getId().equals(id)) {
                        e.setTitle(r.getTitle());
                    }
                }
            }
        }
        String fileName = URLEncoder.encode("评价管理列表", "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), RideMarkingListData.class)
                .sheet(0)
                .doWrite(evaluationListData);
        return null;
    }

    /**
     * 评价详情
     *
     * @param id
     * @return
     */
    @Override
    public RestResult<RideMarkingDetailsPresenter> evaluationDetails(Long id) {
        RideMarking rideMarking = rideMarkingMapper.selectById(id);
        if (ObjectUtils.isEmpty(rideMarking)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        RideMarkingDetailsPresenter evaluationDetailsPresenter = rideMarkingMapper.evaluationDetails(id);
        if (ObjectUtils.isEmpty(evaluationDetailsPresenter)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
//        Ride ride = rideMapper.selectById(id);
//        if (ObjectUtils.isEmpty(ride)) {
//            return RestResult.failed("行程信息不存在");
//        }
        //查询标签
        Long[] tag = new Long[0];
        Long[] longs = rideMarkingTagMapper.selectTag(id);
        if (ObjectUtils.isEmpty(longs)) {
            evaluationDetailsPresenter.setTag(tag);
        } else {
            evaluationDetailsPresenter.setTag(longs);
        }
        return RestResult.success(evaluationDetailsPresenter);
    }
}
